package bb.lanxing.activity.bluetooth;

import java.text.DecimalFormat;
import java.util.regex.Pattern;

import org.apache.commons.cli.HelpFormatter;
import org.json.JSONObject;

import com.github.mikephil.charting.utils.Utils;
import com.orm.query.Condition;
import com.orm.query.Select;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.base.BaseDisplayActivity;
import bb.lanxing.calc.calculator.PTAltitudeCalc;
import bb.lanxing.calc.data.DisplayPoint;
import bb.lanxing.lib.devices.base.DeviceContext;
import bb.lanxing.lib.devices.ble.dfu.DfuContext;
import bb.lanxing.lib.devices.ble.dfu.IDfuProgressCallback;
import bb.lanxing.lib.devices.utils.DeviceVersionHelper;
import bb.lanxing.manager.RemoteSharedPreference;
import bb.lanxing.manager.SPConstant;
import bb.lanxing.model.database.Device;
import bb.lanxing.network.BiCiCallback;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.view.BiciAlertDialogBuilder;
import kotlinx.coroutines.DebugKt;

public class SmartAssistDeviceActivity extends BaseDisplayActivity implements IDfuProgressCallback {
    private ImageView batteryView;
    private TextView cadenceWheelDiameter;
    private TextView deviceName;
    private TextView distanceView;
    private TextView elevationView;
    private TextView firmwareVersionView;
    private PTAltitudeCalc mAltitudeCalculator;
    private View mCadenceWheelLayout;
    private BroadcastReceiver mDataReceiver;
    private DecimalFormat mDecimalFormatter_1_bits;
    private DecimalFormat mDecimalFormatter_2_bits;
    private Device mDevice;
    private DfuContext mDfuContext;
    private ProgressDialog mDfuProgressDialog;
    private View mIbUpgradeFirmware;
    private View mTvUnbindDevice;
    private TextView pressureView;
    private ImageView qiLogo;
    private TextView rpmView;
    private TextView temperatureView;
    private ImageButton upgradeFirmware;
    private final String EMPTY_DATA = HelpFormatter.DEFAULT_LONG_OPT_PREFIX;
    private final int[] mBatteryIcons = {
            R.drawable.ic_status_battery_0,
            R.drawable.ic_status_battery_1,
            R.drawable.ic_status_battery_2,
            R.drawable.ic_status_battery_3,
            R.drawable.ic_status_battery_4,
            R.drawable.ic_status_battery_5,
            R.drawable.ic_status_battery_6};

    private void unbindDevice() {
    }

    @Override
    public void onError(int i, int i2, String str) {
    }

    @Override
    public void onUpgradeStarted() {
    }

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        Device byAddress = Device.getByAddress(getIntent().getStringExtra("EXTRA_DEVICE_ADDRESS"));
        this.mDevice = byAddress;
        if (byAddress == null) {
            finish();
            return;
        }
        setContentView(R.layout.activity_smart_assist_device);
        bindView(getWindow().getDecorView());
        setupActionBar(true);
        setTitle(getString(R.string.device_qi_title));
        this.mDecimalFormatter_2_bits = new DecimalFormat("#.##");
        this.mDecimalFormatter_1_bits = new DecimalFormat("#.#");
        float f = RemoteSharedPreference.getInstance().getFloat(SPConstant.KEY_WHEEL_LENGTH, 2.171f);
        TextView textView = this.cadenceWheelDiameter;
        textView.setText(((int) (f * 1000.0f)) + " mm");
        registerDataReceiver();
        handleBattery(null);
        handleCadenceData(null);
        requestBattery();
        requestFirmwareVersion();
        if (this.mDevice.getDeviceNumber() == 0) {
            uploadDeviceInfo();
        }
        setLogo(null);
    }

    private void setLogo(String str) {
        if (str == null) {
            str = DeviceVersionHelper.getLocalVersion(getApplicationContext(), this.mDevice.getAddress());
        }
        if (isPro(str)) {
            this.qiLogo.setImageResource(R.drawable.ic_default);
        } else {
            this.qiLogo.setImageResource(R.drawable.ic_default);
        }
    }

    private void uploadDeviceInfo() {
        new BiCiCallback() {
            @Override
            public void onResponseString(@NonNull String str) {
                try {
                    mDevice.setDeviceNumber(new JSONObject(str).getInt("deviceServerId"));
                    mDevice.save();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        Device device = (Device) Select.from(Device.class).where(Condition.prop("address").eq(this.mDevice.getAddress())).first();
    }

    @Override
    public void onStart() {
        super.onStart();
        registerDataReceiver();
    }

    @Override
    public void onStop() {
        super.onStop();
        unregisterDataReceiver();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DfuContext dfuContext = this.mDfuContext;
        if (dfuContext != null) {
            dfuContext.release();
            this.mDfuContext = null;
        }
    }

    private void registerDataReceiver() {
        if (this.mDataReceiver != null) {
            return;
        }
        this.mDataReceiver = new CadenceDataReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("ACTION_CADENCE_DATAS");
        intentFilter.addAction("ACTION_BATTERY");
        intentFilter.addAction("ACTION_PRESSURE_DATAS");
        intentFilter.addAction("ACTION_DEVICE_INFORMATION");
        registerReceiver(this.mDataReceiver, intentFilter);
    }

    private void unregisterDataReceiver() {
        BroadcastReceiver broadcastReceiver = this.mDataReceiver;
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver);
            this.mDataReceiver = null;
        }
    }

    private void cadenceWheelSetting() {
        showWheelSettingDialog();
    }

    private void unBoundDeviceConfirm() {

        new BiciAlertDialogBuilder(this)
                .setTitle(R.string.st_forget_sensor)
                .setMessage(R.string.st_are_you_sure_unbind)
                .setPositiveButton(R.string.mine_profile_dialog_btn_unbind, (dialogInterface, i) -> {
                    if (mDevice.getDeviceNumber() > 0) {
                        MyHttpClient.deleteDevice(mDevice.getDeviceNumber());
                    }
                    Device.deleteAll(Device.class, "type = ? and userId = ?", String.valueOf(6), String.valueOf(App.getContext().getUserId()));
                    App.getContext().disconnectDevice(6);
                    DeviceContext.startAndRefreshAutoConnector();
                    finish();
                })
                .setNegativeButton(R.string.str_sync_cancel, (dialogInterface, i) -> {
                }).show().setCanceledOnTouchOutside(true);
    }

    private void upgradeFirmware() {
        new AlertDialog.Builder(this)
                .setMessage(getString(R.string.message_upgrade_fw_confirm, this.mDevice.getName()))
                .setPositiveButton(R.string.str_sync_confirm, (dialogInterface, i) -> {
                    try {
                        SmartAssistDeviceActivity.this.startUpgrade();
                    } catch (Throwable e) {
                        throw new RuntimeException(e);
                    }
                })
                .setNegativeButton(R.string.cancel, (DialogInterface.OnClickListener) null).show();
    }

    public void startUpgrade() throws Throwable {
        if (this.mDfuContext == null) {
            Device device = this.mDevice;
            this.mDfuContext = new DfuContext(this, device, device.getLocalFwFilePath(), this);
        }
        this.mDfuContext.enterDfuMode();
    }

    private void handleCadenceData(DisplayPoint displayPoint) {
        CharSequence charSequence;
        CharSequence charSequence2;
        CharSequence charSequence3;
        CharSequence charSequence4;
        CharSequence charSequence5 = HelpFormatter.DEFAULT_LONG_OPT_PREFIX;
        if (displayPoint != null) {
            int cadence = displayPoint.getCadence(0);
            float pressure = displayPoint.getPressure();
            float temperature = displayPoint.getTemperature(0.0f);
            double altitude = displayPoint.getAltitude(Utils.DOUBLE_EPSILON);
            charSequence5 = buildParamSpan(cadence, R.string.str_fm_unit_rpm, 30);
            charSequence = buildParamSpan(this.mDecimalFormatter_1_bits.format(displayPoint.getSpeed(Utils.DOUBLE_EPSILON) * 3.6d), R.string.str_fm_unit_km_h, 30);
            String format = this.mDecimalFormatter_2_bits.format(pressure);
            String format2 = this.mDecimalFormatter_2_bits.format(temperature);
            String format3 = this.mDecimalFormatter_2_bits.format(altitude);
            charSequence3 = buildParamSpan(format, R.string.str_fm_unit_hPa_with_space, 18);
            charSequence4 = buildParamSpan(format2, R.string.str_fm_unit_c_with_space, 18);
            charSequence2 = buildParamSpan(format3, R.string.str_fm_unit_m_with_space, 18);
        } else {
            charSequence = charSequence5;
            charSequence2 = charSequence;
            charSequence3 = charSequence2;
            charSequence4 = charSequence3;
        }
        this.rpmView.setText(charSequence5);
        this.distanceView.setText(charSequence);
        this.pressureView.setText(charSequence3);
        this.temperatureView.setText(charSequence4);
        this.elevationView.setText(charSequence2);
    }

    public void handleBattery(Intent intent) {
        int i = 1;
        if (intent != null) {
            int intExtra = intent.getIntExtra("EXTRA_BATTERY", 0);
            int[] iArr = this.mBatteryIcons;
            int length = iArr.length - 1;
            if (intExtra < 15) {
                i = 0;
            } else if (intExtra >= 30) {
                i = intExtra < 45 ? 2 : intExtra < 60 ? 3 : intExtra < 75 ? 4 : intExtra < 90 ? 5 : length;
            }
            this.batteryView.setImageResource(iArr[i]);
            return;
        }
        ImageView imageView = this.batteryView;
        int[] iArr2 = this.mBatteryIcons;
        imageView.setImageResource(iArr2[iArr2.length - 1]);
    }

    public void handleDeviceInformation(Intent intent) {
        String stringExtra = intent.getStringExtra("EXTRA_DEVICE_INFORMATION");
        if (TextUtils.isEmpty(stringExtra)) {
            return;
        }
        setLogo(stringExtra);
        DeviceVersionHelper.setLocalVersion(getApplicationContext(), mDevice.getAddress(), stringExtra);
        this.mDevice.setDeviceFwName(stringExtra);
        this.mDevice.save();

        this.firmwareVersionView.setVisibility(View.VISIBLE);
        this.firmwareVersionView.setText(getString(R.string.device_qi_label_fw_ver, stringExtra));
        if (isPro(stringExtra)) {
            return;
        }
        ImageButton imageButton = this.upgradeFirmware;
        if (this.mDevice.isNeedUpgrade()) {
            imageButton.setVisibility(View.VISIBLE);
        } else {
            imageButton.setVisibility(View.GONE);
        }

    }

    private boolean isPro(String str) {
        if (str == null) {
            return false;
        }
        return Pattern.compile("2\\..*\\..*").matcher(str).matches();
    }

    private void requestBattery() {

        this.batteryView.postDelayed(() -> {
            Intent intent = new Intent("ACTION_REQUEST_BATTERY");
            intent.putExtra("EXTRA_DEVICE_TYPE", 6);
            intent.putExtra("EXTRA_DEVICE_ADDRESS", mDevice.getAddress());
            sendOrderedBroadcast(intent, null);
        }, 1000L);
    }

    private void requestFirmwareVersion() {
        Intent intent = new Intent("ACTION_REQUEST_DEVICE_INFORMATION");
        intent.putExtra("EXTRA_DEVICE_TYPE", 6);
        intent.putExtra("EXTRA_DEVICE_ADDRESS", mDevice.getAddress());
        sendOrderedBroadcast(intent, null);
    }

    private CharSequence buildParamSpan(Object obj, int i, int i2) {
        String string = getString(i);
        String valueOf = String.valueOf(obj);
        String format = String.format(string, obj);
        int indexOf = format.indexOf(valueOf);
        AbsoluteSizeSpan absoluteSizeSpan = new AbsoluteSizeSpan(i2, true);
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(format);
        spannableStringBuilder.setSpan(absoluteSizeSpan, indexOf, valueOf.length() + indexOf, 33);
        return spannableStringBuilder;
    }

    private void showWheelSettingDialog() {

        new BiciAlertDialogBuilder(this)
                .setItems(new String[]{getString(R.string.mine_wheel_setting_dialog_item_custom),
                        getString(R.string.mine_wheel_setting_dialog_item_check_table)}, (dialogInterface, i) -> {
                            Intent intent = new Intent(SmartAssistDeviceActivity.this, WheelLengthSetting.class);
                            if (i == 0) {
                                intent.putExtra(DebugKt.DEBUG_PROPERTY_VALUE_AUTO, false);
                            } else {
                                intent.putExtra(DebugKt.DEBUG_PROPERTY_VALUE_AUTO, true);
                            }
                            startActivityForResult(intent, 76);
                        }).show();
    }

    @Override
    public void onActivityResult(int i, int i2, Intent intent) {
        super.onActivityResult(i, i2, intent);
        DfuContext dfuContext = this.mDfuContext;
        if (dfuContext != null) {
            try {
                dfuContext.parseDfuFile(i, i2, intent);
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
        }
        if (i2 == -1 && i == 76 && intent != null) {
            float floatExtra = intent.getFloatExtra("wheelDiameterLength", RemoteSharedPreference.getInstance().getFloat(SPConstant.KEY_WHEEL_LENGTH, 2.171f));
            TextView textView = this.cadenceWheelDiameter;
            textView.setText(((int) (floatExtra * 1000.0f)) + " mm");
        }
    }

    public void showProgressDialog(CharSequence charSequence) {
        ProgressDialog progressDialog = this.mDfuProgressDialog;
        if (progressDialog == null) {
            ProgressDialog show = ProgressDialog.show(this, null, charSequence, true, true,
                    dialogInterface -> mDfuContext.abort());
            this.mDfuProgressDialog = show;
            show.setCanceledOnTouchOutside(false);
            this.mDfuProgressDialog.setCancelable(false);
            return;
        }
        progressDialog.setMessage(charSequence);
        this.mDfuProgressDialog.show();
    }

    public void dismissProgressDialog() {
        ProgressDialog progressDialog = this.mDfuProgressDialog;
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    @Override
    public void onDfuProcessMessage(String str) {
        showProgressDialog(str);
    }

    @Override
    public void onProgressChanged(int i) {
        showProgressDialog(getString(R.string.message_upgrade_fw_in_progress, i));
    }

    @Override
    public void onUpgradeCompleted() {
        dismissProgressDialog();

        new AlertDialog.Builder(this)
                .setMessage(R.string.message_upgrade_fw_on_success)
                .setPositiveButton(R.string.str_sync_confirm, (dialogInterface, i) -> finish())
                .setCancelable(false).show().setCanceledOnTouchOutside(false);
    }

    @Override
    public void onUpgradeFail(String str) {
        dismissProgressDialog();
        new AlertDialog.Builder(this)
                .setMessage(R.string.message_upgrade_fw_fail)
                .setPositiveButton(R.string.str_sync_confirm, (dialogInterface, i) -> {
                    try {
                        startUpgrade();
                    } catch (Throwable e) {
                        throw new RuntimeException(e);
                    }
                })
                .setNegativeButton(R.string.cancel, (dialogInterface, i) -> new AlertDialog.Builder(SmartAssistDeviceActivity.this)
                                .setMessage(R.string.message_upgrade_fw_exit)
                                .setPositiveButton(R.string.str_sync_confirm, (DialogInterface.OnClickListener) null)
                                .setOnDismissListener(dialogInterface2 -> finish()).show())
                .setCancelable(false)
                .show()
                .setCanceledOnTouchOutside(false);
    }

    @Override
    protected void onRefreshUI(DisplayPoint displayPoint) {
        handleCadenceData(displayPoint);
    }

    private void bindView(View view) {
        this.rpmView = (TextView) view.findViewById(R.id.tv_rpm);
        this.distanceView = (TextView) view.findViewById(R.id.tv_distance);
        this.pressureView = (TextView) view.findViewById(R.id.tv_pressure);
        this.elevationView = (TextView) view.findViewById(R.id.tv_elevation);
        this.temperatureView = (TextView) view.findViewById(R.id.tv_temperature);
        this.batteryView = (ImageView) view.findViewById(R.id.tv_battery);
        this.qiLogo = (ImageView) view.findViewById(R.id.iv_qi_logo);
        this.firmwareVersionView = (TextView) view.findViewById(R.id.firmware_version);
//        this.upgradeFirmware = (ImageButton) view.findViewById(R.id.ib_upgrade_firmware);
        this.cadenceWheelDiameter = (TextView) view.findViewById(R.id.cadenceWheelView);
        this.deviceName = (TextView) view.findViewById(R.id.tv_device_name);
        this.mCadenceWheelLayout = view.findViewById(R.id.cadenceWheelLayout);
        this.mTvUnbindDevice = view.findViewById(R.id.tv_unbind_device);
        this.mIbUpgradeFirmware = view.findViewById(R.id.ib_upgrade_firmware);

        this.mCadenceWheelLayout.setOnClickListener(view2 -> cadenceWheelSetting());
        this.mTvUnbindDevice.setOnClickListener(view2 -> unBoundDeviceConfirm());
        this.mIbUpgradeFirmware.setOnClickListener(view2 -> upgradeFirmware());
    }


    public class CadenceDataReceiver extends BroadcastReceiver {
        CadenceDataReceiver() {
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null) {
                return;
            }

            if (action.equals("ACTION_BATTERY") && intent.getIntExtra("EXTRA_DEVICE_TYPE", 0) == 6) {
                handleBattery(intent);
            } else if (action.equals("ACTION_DEVICE_INFORMATION") && intent.getIntExtra("EXTRA_DEVICE_TYPE", 0) == 6){
                handleDeviceInformation(intent);
            }
        }
    }
}
